<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Controller\Grpc\Client\AdminClient;
use App\Constants\ReturnCode;
use App\Service\TestJobService;
use Grpc\Params;

#[Controller]
class TestController extends AbstractController
{
    #[Inject]
    protected TestJobService $testJobService;

    #[RequestMapping(path: 'index', methods: 'post')]
    public function index()
    {
        $array = [
            ['id' => 1, 'name' => 'pid1', 'pid' => 0],
            ['id' => 2, 'name' => 'pid2', 'pid' => 0],
            ['id' => 3, 'name' => 'id3', 'pid' => 1],
            ['id' => 4, 'name' => 'id4', 'pid' => 2],
            ['id' => 5, 'name' => 'id5', 'pid' => 1],
        ];

        $tree = array_to_tree($array);

        return $this->result(ReturnCode::SUCCESS, $tree);
    }

    #[RequestMapping(path: 'queue', methods: 'POST')]
    public function queue()
    {
        $this->testJobService->test(['id' => 1]);

        return $this->result(ReturnCode::SUCCESS);
    }

    #[RequestMapping(path: 'grpc', methods: 'POST')]
    public function grpc()
    {
        $admin_id = $this->request->post('id', 0);
        
        $client = new AdminClient('127.0.0.1:9502', [ 'credentials' => null, ]);

        $request = new Params();

        $request->setMessage(json_encode(['admin_id' => $admin_id], JSON_UNESCAPED_UNICODE));

        list($reply, $status) = $client->GetInfo($request);

        if ($status !== 0) throw new \Exception($reply);

        $message = json_decode($reply->getMessage(), true);
        
        return $this->result(ReturnCode::SUCCESS, $message);
    }
}
